package com.jhf.skypac_pda.fragment;

import android.content.Intent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jhf.skypac_pda.LoginActivity;
import com.jhf.skypac_pda.R;
import com.jhf.skypac_pda.base.BaseFragment;
import com.jhf.skypac_pda.db.impl.PermissionDaoImp;
import com.jhf.skypac_pda.model.UserListModel;
import com.jhf.skypac_pda.utils.PrefUtils;
import com.jhf.skypac_pda.utils.Urls;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static okgo.utils.HttpUtils.runOnUiThread;

/**
 * Created by sunshine on 2020/7/23.
 */
public class MineFragment extends BaseFragment {
    @BindView(R.id.tv_user)
    TextView tvUser;
    @BindView(R.id.tv_nickname)
    TextView tvNickname;
    @BindView(R.id.tv_phonenum)
    TextView tvPhonenum;
    @BindView(R.id.tv_email)
    TextView tvEmail;
    @BindView(R.id.tv_department)
    TextView tvDepartment;
    @BindView(R.id.tv_date)
    TextView tvDate;
    @BindView(R.id.tv_roles)
    TextView tvRoles;

    private ArrayList<UserListModel> mList = new ArrayList<>();
    private ArrayList<String> mPermissionList = new ArrayList<>();
    private String userName = "";
    private String nickName = "";
    private String createTime = "";
    private String roles = "";

    public static MineFragment newInstance() {
        return new MineFragment();
    }

    @Override
    protected void setUpContentView() {
        setContentView(R.layout.fragment_mine);
    }

    @Override
    protected void setUpView(View view) {

    }

    @Override
    protected void setUpComponent() {

    }

    @Override
    protected void setUpData() {
        //userName.setText(BaseApplication.getIntance().getLoginBean().getUsername());
        /*userName.setText(PrefUtils.getString(getActivity(), "userName", ""));
        try {
            tv_version.setText("版本号: v" + Utils.getVersion(getActivity()));
        } catch (Exception e) {
            e.printStackTrace();
        }*/
    }

    @OnClick({R.id.btnLogout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btnLogout:
                PrefUtils.setString(getActivity(), "userName", "");
                PrefUtils.setString(getActivity(), "password", "");
                startActivity(new Intent(getActivity(), LoginActivity.class));
                getActivity().finish();
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // 目标URL
                    String targetURL = Urls.URL_USERINFO;
                    // 创建URL对象
                    URL url = new URL(targetURL);
                    // 打开连接
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                    // 设置请求方法为GET
                    connection.setRequestMethod("GET");
                    connection.setRequestProperty("Authorization", PrefUtils.getString(getActivity(), "token", ""));

                    // 接收响应码
                    int responseCode = connection.getResponseCode();
                    System.out.println("Response Code: " + responseCode);

                    // 如果响应码是HTTP_OK（200）
                    if (responseCode == HttpURLConnection.HTTP_OK) {
                        // 新建BufferedReader读取响应
                        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                        String inputLine;
                        StringBuilder response = new StringBuilder();

                        // 读取服务器响应并显示
                        while ((inputLine = in.readLine()) != null) {
                            response.append(inputLine);
                        }
                        in.close();

                        JSONObject jsonObject = new JSONObject(response.toString());
                        if (jsonObject.has("user")) {
                            userName = jsonObject.getJSONObject("user").getString("userName");
                            nickName = jsonObject.getJSONObject("user").getString("nickName");
                            //String phonenumber = jsonObject.getJSONObject("user").getString("phonenumber");
                            //String email = jsonObject.getJSONObject("user").getString("email");
                            //String deptName = jsonObject.getJSONObject("user").getString("deptName");
                            createTime = jsonObject.getJSONObject("user").getString("createTime");



                            Gson gg = new Gson();
                            Type listType = new TypeToken<List<UserListModel>>() {
                            }.getType();
                            mList = gg.fromJson(jsonObject.getJSONObject("user").getString("roles"), listType);
                            roles = "";
                            for (UserListModel userListModel:
                                    mList) {
                                roles = roles + ", " + userListModel.getRoleName();
                            }
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    tvUser.setText(userName);
                                    tvNickname.setText(nickName);
                                    tvDate.setText(createTime);
                                    //tvDepartment.setText(deptName);
                                    //tvPhonenum.setText(phonenumber);
                                    //tvEmail.setText(email);

                                    tvRoles.setText(roles.substring(1));
                                }
                            });
                        }

                        if (jsonObject.has("permissions")) {
                            Gson gg = new Gson();
                            Type listType = new TypeToken<List<String>>() {
                            }.getType();
                            mPermissionList = gg.fromJson(jsonObject.getString("permissions"), listType);
                            PrefUtils.setBoolean(getActivity(), "isAdmin", false);
                            if (mPermissionList.get(0).equals("*:*:*")) {
                               PrefUtils.setBoolean(getActivity(), "isAdmin", true);
                               return;
                            }

                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    //登录之后要重新清理和保存权限表
                                    PermissionDaoImp.getInstance(getActivity()).deleteAll();
                                    PermissionDaoImp.getInstance(getActivity()).savePermissions(mPermissionList);
                                }
                            });
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getActivity(), e.getMessage(),Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        }).start();
    }
}
